var ZYRequestClient = require("../../../utils/zy-request");
var requestClient;
var socketTask;
const app = getApp();
Page({
  data: {
   companyId:0,
   level:0,
   showCreateCompany:false,
   showDepartment:false,
   showDepartmentAction:false,
   showUserAction:false,
   showAddDialog:false,
   showUpdateDialog:false,
   checkDepartmentId:0,
   showCheckDialog:false,
   companyName:"暂无公司",
   belongUserName:"无",
   departmentName:"",
   departmentList:[],
   selectedDepartment:null,
   selectedUser:null,
   userList:[],
   departmentActionButtons:[{text:'编辑部门',value:'edit'},{text:'解散部门',type: 'warn',value:'remove'}],
   userActionButtons:[{text:'归属到部门',value:'move'},{text:'修改人员备注',value:'update'},{text:'解除公司绑定',type: 'warn',value:'remove'}],

   navbarData:{
    showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
    title: '通讯录', //导航栏 中间的标题
    white:true
   },
   // 导航头的高度
   height: app.globalData.height * 2 + 20
  },
  onLoad: function () {
    requestClient = new ZYRequestClient();
  },
  onShow: function () {
    var _this = this;
    // 加载公司部门和人员
    var userInfo = wx.getStorageSync('userInfo');
    if(userInfo==''){
      wx.showModal({
        title:'授权登录',
        content:'请授权登录使用更多功能！',
        showCancel:false,
        success(r){
          wx.navigateTo({
            url: '../../login/index',
          })
        }
      })
      _this.setData({
        showCreateCompany:true,
        showDepartment:false
      });
    } else {
      requestClient.getUserDefaultCompany(userInfo.id,function(res){
        if(res.data.data == null){
          _this.setData({
            showCreateCompany:true,
            showDepartment:false
          });
          return;
        } else {
          var defaultCompany = wx.getStorageSync('defaultCompany');
          _this.setData({
            companyId:defaultCompany.id,
            companyName:defaultCompany.name,
            belongUserName:defaultCompany.userInfo.nickName,
            showCreateCompany:false,
            showDepartment:true
          });
          _this.loadDefaultCompany();
        }
      });
      // 创建关闭websocket
      socketTask = requestClient.connectSocket();
      socketTask.onOpen(function(){
        // 连接成功获取审批状态
        var data = {
          'userId':userInfo.id,
          'operateType':'wait_approval'
        };
        socketTask.send({
          data:JSON.stringify(data)
        });
      });
      // 数据监听
      socketTask.onMessage(function(response){
        var messageData = JSON.parse(response.data);
        if(messageData.operateType == "wait_approval"){
          if(messageData.hasApproval){
            wx.showTabBarRedDot({
              index: 2,
              text: ''
            })
          } else {
            wx.removeTabBarBadge({
              index:2
            });
          }
        }
      });
    }
  },
  onHide(){
    // 关闭websocket
    if(socketTask){
      socketTask.close();
      socketTask = null;
    }
  },
  // 加载公司资源
  loadDefaultCompany(){
    var _this = this;
    requestClient.getCompanyResource(_this.data.companyId,function(resource){
    _this.setData({
      departmentList:resource.data.data.departmentVoList,
      userList:resource.data.data.userVoList
    });
  });
  },
  // 下拉刷新
  onPullDownRefresh(e){
    this.onShow();
    wx.stopPullDownRefresh();
  },
  // 跳转下级部门
  bindDepartmentClick:function(e){
    var _this = this;
    var department = e.currentTarget.dataset.department;
    wx.navigateTo({
      url: 'userlist/index?parentId=' + department.id + "&name=" + department.name + "&level=1&companyId=" + _this.data.companyId,
    });
  },
  // 邀请人员
  bindInviteUser:function(e){
    var _this = this;
    requestClient.checkFunctionPermission(3001,'您没有权限邀请人员，请联系企业创建者！',function(){
      wx.navigateTo({
        url: '../mine/inviteuser/index?companyId=' + _this.data.companyId,
      })
    });
  },
  // 显示添加部门
  showAddDepartment:function(){
    var _this = this;
    requestClient.checkFunctionPermission(3004,'您没有权限添加部门，请联系企业创建者！',function(){
      _this.setData({
        departmentName:"",
        showAddDialog:true
      });
    });
  },
  // 长按显示部门操作菜单
  bindDepartmentLongPress:function(e){
    var _this = this;
    _this.setData({
      selectedDepartment:e.currentTarget.dataset.department
    });
    _this.setData({showDepartmentAction:true});
  },
  // 部门操作按钮
  bindDepartmentActionTap:function(e){
    var _this = this;
    _this.setData({showDepartmentAction:false});
    if(e.detail.value == "edit"){
      _this.setData({
        departmentName:"",
        showUpdateDialog:true
      });
    } else {
      wx.showModal({
        title:"解散部门",
        content:"您确定要解散此部门吗？",
        success(e){
          if(e.confirm){
            requestClient.checkFunctionPermission(3006,'您没有权限解散部门，请联系企业创建者！',function(){
              // 解散部门
              requestClient.removeDepartment(_this.data.selectedDepartment.id,function(res){
                // 加载公司资源
                requestClient.getCompanyResource(_this.data.companyId,function(resource){
                  _this.setData({
                    departmentList:resource.data.data.departmentVoList,
                    userList:resource.data.data.userVoList
                  });
                });
              })
            });
          }
        }
      })
    }
  },
  // 跳转用户信息
  bindUserClick:function(e){
    requestClient.checkFunctionPermission(3007,'您没有权限查看人员，请联系企业创建者！',function(){
      var user = e.currentTarget.dataset.user;
      wx.navigateTo({
        url: 'userinfo/index?id=' + user.id
      });
    });
  },
  // 长按显示用户操作菜单
  bindUserLongPress:function(e){
    var _this = this;
    _this.setData({
      selectedUser:e.currentTarget.dataset.user,
      showUserAction:true
    });
  },
  // 用户操作按钮
  bindUserActionTap:function(e){
    var _this = this;
    _this.setData({showUserAction:false});
    var operate = e.detail.value;
    if(operate == "move"){
      _this.setData({
        showCheckDialog:true
      });
    } else if(operate == "update"){
      _this.setData({
        showUserAliasDialog:true
      });
    } else {
      // 判断是否为本人操作
      var userInfo = wx.getStorageSync('userInfo');
      if(userInfo.id == _this.data.selectedUser.id){
        wx.showModal({
          title:'解绑人员',
          content:'如果您想退出当前企业，可以在我的企业选择退出！',
          showCancel:false,
          success(r){

          }
        })
        return;
      }
      wx.showModal({
        title:"解除绑定",
        content:"您确定要解除用户"+_this.data.selectedUser.nickName + "的绑定吗？",
        success(r){
          if(r.confirm){
            requestClient.checkFunctionPermission(3003,'您没有权限解除人员绑定，请联系企业创建者！',function(){
              // 只有超级管理员才可以删除管理员
              if(_this.checkAdmin(_this.data.selectedUser.id)){
                if(_this.checkSuperAdmin()){
                  requestClient.removeUser(_this.data.selectedUser.id,_this.data.companyId,function(res){
                      // 加载公司资源
                      requestClient.getCompanyResource(_this.data.companyId,function(resource){
                        _this.setData({
                          departmentList:resource.data.data.departmentVoList,
                          userList:resource.data.data.userVoList
                        });
                      });
                  });
                } else {
                  wx.showModal({
                    title:'没有权限',
                    content:'当前用户为管理员，只有企业的创建者才能解除绑定！',
                    showCancel:false,
                    success(r){

                    }
                  })
                }
              }  else {
                requestClient.removeUser(_this.data.selectedUser.id,_this.data.companyId,function(res){
                  // 加载公司资源
                    requestClient.getCompanyResource(_this.data.companyId,function(resource){
                      _this.setData({
                        departmentList:resource.data.data.departmentVoList,
                        userList:resource.data.data.userVoList
                      });
                    });
                });
              }
            });
          }
        }
      })
    }
  },
  checkAdmin(userId){
      var defaultCompany = wx.getStorageSync('defaultCompany');
      if(userId == defaultCompany.belongUser){
        return true;
      }
      var adminList = defaultCompany.adminList;
      for(var i = 0; i < adminList.length; i++){
        if(userId == adminList[i].id){
          return true;
        }
      }

      return false;
  },
  checkSuperAdmin(){
    var userInfo = wx.getStorageSync('userInfo');
    var defaultCompany = wx.getStorageSync('defaultCompany');
    if(userInfo.id == defaultCompany.belongUser){
      return true;
    }

    return false;
},
  // 添加输入框
  formInputChange:function(e){
      this.setData({
        departmentName:e.detail.value
      });
  },
  // 更新输入框
  formUpdateInputChange:function(e){
    this.setData({
      departmentName:e.detail.value
    });
  },
  // 添加部门
  bindAddDepartment:function(e){
    var _this = this;
    _this.setData({
      showAddDialog:false
    });
    if(e.detail.index == 0){
      return ;
    }
    var name = _this.data.departmentName;
    if(name == "" || name.trim() == ""){
        wx.showToast({
          title:"名称不能为空!",
          icon:"error"
        });
        return;
    }
    var userInfo = wx.getStorageSync('userInfo');
    // 构建部门数据
    var departmentData = {
      parentId:_this.data.companyId,
      name:name,
      level:_this.data.level,
      companyId:_this.data.companyId,
      createUser:userInfo.id
    };
      requestClient.checkFunctionPermission(3004,'您没有权限添加部门，请联系企业创建者！',function(){
        requestClient.addCompanyDepartment(departmentData,function(res){
            // 加载公司资源
            requestClient.getCompanyResource(_this.data.companyId,function(resource){
              _this.setData({
                departmentList:resource.data.data.departmentVoList,
                userList:resource.data.data.userVoList
              });
            });
        });
      });
  },
  // 更新部门名称
  bindUpdateDepartment:function(e){
    var _this = this;
    _this.setData({
      showUpdateDialog:false
    });
    if(e.detail.index == 0){
      return ;
    }
    var name = _this.data.departmentName;
    if(name == "" || name.trim() == ""){
        wx.showToast({
          title:"名称不能为空!",
          icon:"error"
        });
        return;
    }
    requestClient.checkFunctionPermission(3005,'您没有权限编辑部门，请联系企业创建者！',function(){
      requestClient.updateDepartmentName(name,_this.data.selectedDepartment.id,function(res){
        // 加载公司资源
        requestClient.getCompanyResource(_this.data.companyId,function(resource){
              _this.setData({
                departmentList:resource.data.data.departmentVoList,
                userList:resource.data.data.userVoList
              });
            });
        });
    });
  },
  // 修改人员备注
  bindUpdateUserAlias(e){
    var _this = this;
    _this.setData({
      showUserAliasDialog:false
    });
    if(e.detail.index == 0){
      return ;
    }
    var userAlias = _this.data.userAlias;
    if(userAlias == "" || userAlias.trim() == ""){
        wx.showToast({
          title:"备注不能为空!",
          icon:"error"
        });
        return;
    }
    requestClient.checkFunctionPermission(3009,'您没有权限修改人员备注，请联系企业创建者！',function(){
      requestClient.updateUserAlias(_this.data.selectedUser.id,_this.data.companyId,userAlias,function(res){
        // 加载公司资源
        requestClient.getCompanyResource(_this.data.companyId,function(resource){
              _this.setData({
                departmentList:resource.data.data.departmentVoList,
                userList:resource.data.data.userVoList
              });
            });
        });
    });
  },
  formUpdateUserAliasChange(e){
    this.setData({
      userAlias:e.detail.value
    });
  },
  // 确认勾选移动的部门
  bindSelectedDepartmentClick(e){
    var _this = this;
    _this.setData({
      showCheckDialog:false
    });
    if(_this.data.checkDepartmentId == 0){
      wx.showToast({
        title: '请选择部门!',
        icon:'error',
        mask:true
      })
      return;
    }
    var moveUser = {
      userId:_this.data.selectedUser.id,
      departmentId:_this.data.checkDepartmentId,
      companyId:_this.data.companyId
    };
    requestClient.checkFunctionPermission(3002,'您没有权限移动人员到部门，请联系企业创建者！',function(){
      requestClient.moveDownCompanyUser(moveUser,function(){
        _this.onShow();
      });
    });
  },
  // 部门勾选变化
  checkboxChange(e){
    this.setData({
      checkDepartmentId:e.detail.value
    });
  },
  // 创建企业
  bindCreateCompany(e){
    wx.navigateTo({
      url: '../mine/createcompany/index'
    })
  }
})